<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of strategy
 *
 * @author Samuel
 */
defined('BASEPATH') or die('forbidden');

class Strategy_Controller extends Controller {
    private $strategy_array;
    private $wholeServerHost;
    public function _init() {
        check_level(50, segment(0), segment(1), segment(2, 'index'));
        $this->strategy_array = array('lastarea'=>  translate('GENERAL_STRATEGY_LASTAREA'),'randarea' => translate('GENERAL_STRATEGY_RANDAREA'));
        $config = get_config();
        $this->wholeServerHost = $config['host_url'];
    }

    function index() {
        $this->view->display("general/strategy/index");
    }

    function flexigrid() {
        list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();
        $rows = array();

        $sql = "SELECT COUNT(*) AS num FROM {pre}area_strategy WHERE {$where}";
        $one = $this->db->one($sql);
        $total = $one['num'];
        $orderby = $sortname ? "ORDER BY {$sortname} {$sortorder}" : "";
        $this->db->query("SELECT {$colsinfo} FROM {pre}area_strategy WHERE {$where} {$orderby} LIMIT {$offset},{$rp}");
        while ($n = $this->db->get_array('default')) {
            $n['strategy'] = $this->strategy_array[$n['strategy']];
            $rows[] = array('id' => $n['id'], 'cell' => $n);
        }
        $result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
        );
        echo json_encode($result);
    }

    public function edit($id=0) {
        $row = $this->db->one("SELECT * FROM {pre}area_strategy WHERE id='{$id}'");
        if (is_submit()) {
            $rowdata = $_POST['row'];
            $areaIds = $_POST['areaIds'];
            $str = array_to_stringparam($rowdata);

            $areas = implode(",", $areaIds);

            $this->db->execute("UPDATE {pre}area_strategy SET strategy='{$rowdata['strategy']}',areas='$areas'");
            insert_log(translate('MENU_GENERAL_STRATEGY'),translate('EDIT'), NULL, array("strategy"=>$rowdata['strategy'],"areas"=>$areas));
            include_once CONFIGPATH."config.php";

            $n['strategy'] = $row['strategy'].";".$row['areas'];
            $jsonStr = json_encode($n);
            $result = vpost($this->wholeServerHost."strategy={$jsonStr}&action=47");
            if ($result != '0' || $result === FALSE)
                $result = 1;
            cp_tips($result == 0 ? "success" : "error");
        }
        set_area_list_view("arealist");
        $this->view->assign("row", $row);
        $this->view->display("general/strategy/edit");
    }

}
